package com.station.Activitys.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;

/**
 * 项目名称：
 * 类描述：屏幕适配拓展类
 * 创建人：张飞祥
 * 创建时间：2018/04/18 下午2:17
 * 修改人：张飞祥
 * 修改时间：2018/04/18 下午2:17
 * 修改备注：
 */
public class UiUtil {
    public static final String TAG = "UiUtil";

    private static int displayWidth = 0; // 显示器宽
    private static int displayHeight = 0; // 显示器高

    //TODO 解决 解决Andriod全屏时软键盘出现不能把原来的布局给顶上去的变量
    public static View mChildOfContent;
    public static int usableHeightPrevious;
    public static FrameLayout.LayoutParams frameLayoutParams;

    public static int getDisplayWidth(Context context) {
        refresh(context);
        return displayWidth;
    }


    public static int getDisplayHeight(Context context) {
        refresh(context);
        return displayHeight;
    }


    private static void refresh(Context context) {
        if (displayWidth > 0 && displayHeight > 0) {
            return;
        }
        init(context);
    }


    private static void init(Context context) {
        try {
            DisplayMetrics dm = new DisplayMetrics();
            WindowManager wm = (WindowManager) context
                    .getSystemService(Context.WINDOW_SERVICE);
            wm.getDefaultDisplay().getMetrics(dm);
            displayWidth = dm.widthPixels;
            displayHeight = dm.heightPixels;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    /**
     * 将px值转换为sp值，保证文字大小不变
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources()
                .getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }


    /**
     * 将sp值转换为px值，保证文字大小不变
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources()
                .getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 获取当前的densityDpi
     */
    public static float getDmDensityDpi(Context context) {
        DisplayMetrics dm = context.getApplicationContext().getResources().getDisplayMetrics();
        float dmDensityDpi = dm.densityDpi;
        return dmDensityDpi;
    }

    /**
     * 适配当前手机代码中设置的px值（宽度）
     */
    public static int reSizePXWidth(Context context, float pxValue) {
        float XXHDPI = 1080 * 1920;
        int displayWidth = getDisplayWidth(context);
        float scale = 1;
        if (displayWidth <= 720) {
            scale = (float) Math.sqrt(displayWidth * ((float) displayWidth / 720) * 1280 / XXHDPI);
        } else if (displayWidth > 720 && displayWidth < 1440) {
            scale = (float) Math.sqrt(displayWidth * ((float) displayWidth / 1080) * 1920 / XXHDPI);
        } else if (displayWidth >= 1440) {
            scale = (float) Math.sqrt(displayWidth * ((float) displayWidth / 1440) * 2560 / XXHDPI);
        }
        int newPxWidth = (int) (scale * pxValue);
        //        Log.i("UIUtil","width:"+displayWidth+";scale:" + scale+";newPx:"+newPx);
        return newPxWidth;
    }

    /**
     * 适配当前手机代码中设置的px值（高度）
     */

    public static int reSizePXHeight(Context context, float pxValue) {
        float XXHDPI = 1080 * 1920;
        int displayHeight = getDisplayHeight(context);
        float scale = 1;
        if (displayHeight <= 720) {
            scale = (float) Math.sqrt(displayHeight * ((float) displayHeight / 720) * 1280 / XXHDPI);
        } else if (displayHeight > 720 && displayHeight < 1440) {
            scale = (float) Math.sqrt(displayHeight * ((float) displayHeight / 1080) * 1920 / XXHDPI);
        } else if (displayHeight >= 1440) {
            scale = (float) Math.sqrt(displayHeight * ((float) displayHeight / 1440) * 2560 / XXHDPI);
        }
        int newPxHeight = (int) (scale * pxValue);
        //        Log.i("UIUtil","width:"+displayWidth+";scale:" + scale+";newPx:"+newPx);
        return newPxHeight;
    }


    /**
     * 获取状态栏高度
     *
     * @param activity
     * @return
     */
    public static int getStatusBarHeight(Activity activity) {
        int result = 0;
        int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = activity.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }




    /**
     * 设置 activity dialog，宽高跟当前 屏幕宽高比一样
     */
    public static void setActivityWinDialog(Activity activity){
        //设置Theme.Dialog View高度、宽度   在setContentView(id);之后添加以下代码
        WindowManager windowManager = activity.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.width = (int)(display.getWidth()); //设置宽度
        lp.height = (int)(display.getHeight()); //设置高度
        activity.getWindow().setAttributes(lp);
    }

    /**
     * 设置 dialog，宽高跟当前 屏幕宽高比一样
     */
    public static void setWindowDialog(Dialog dialog){

        Window window = dialog.getWindow();
        window.getDecorView().setPadding(0, 0, 0, 0); //消除边距
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;   //设置宽度充满屏幕
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(lp);
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    public static void hideBottomUIMenu(Activity activity) {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = activity.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = activity.getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    /**
     * 判断当前 activity 滑动
     */
    public static void slideUIMenuClose(final Activity activity) {
        activity.getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
                int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                        //布局位于状态栏下方
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                        //全屏
                        View.SYSTEM_UI_FLAG_FULLSCREEN |
                        //隐藏导航栏
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
                if (Build.VERSION.SDK_INT >= 19) {
                    uiOptions |= 0x00001000;
                } else {
                    uiOptions |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
                }
                activity.getWindow().getDecorView().setSystemUiVisibility(uiOptions);
            }
        });
    }

    /**
     * 设置 弹出dialog 也不会出现 虚拟键
     * @param dialog
     */
    public static void showDialogUIMenuClose(final Dialog dialog) {
        dialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        dialog.getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
                int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                        //布局位于状态栏下方
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                        //全屏
                        View.SYSTEM_UI_FLAG_FULLSCREEN |
                        //隐藏导航栏
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
                if (Build.VERSION.SDK_INT >= 19) {
                    uiOptions |= 0x00001000;
                } else {
                    uiOptions |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
                }
                dialog.getWindow().getDecorView().setSystemUiVisibility(uiOptions);
            }
        });
    }


    /**
     * 设置 状态栏图标颜色
     *      true： 黑色
     *      false：白色
     * @param setDark
     * @param activity
     */
    public static void setThemeIconColor(boolean setDark, Activity activity) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            View decorView = activity.getWindow().getDecorView();
            if(decorView != null){
                int vis = decorView.getSystemUiVisibility();
                if(setDark){
                    vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                } else{
                    vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                }
                decorView.setSystemUiVisibility(vis);
            }
        }
    }

    /**
     *
     * 低版本 状态栏 API 19
     *
     */
    @TargetApi(19)
    private static void setTranslucentStatus(boolean on, Activity activity) {
        Window win = activity.getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;

        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    /**
     * 解决Android全屏时软键盘出现不能把原来的布局给顶上去的方法
     */
    public static void AndroidBug5497Workaround(Activity activity) {
        FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);
        mChildOfContent = content.getChildAt(0);
        mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            public void onGlobalLayout() {
                possiblyResizeChildOfContent();
            }
        });
        frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
    }
    private static void possiblyResizeChildOfContent() {
        int usableHeightNow = computeUsableHeight();
        if (usableHeightNow != usableHeightPrevious) {
            int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
            int heightDifference = usableHeightSansKeyboard - usableHeightNow;
            if (heightDifference > (usableHeightSansKeyboard/4)) {
                // keyboard probably just became visible
                frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
            } else {
                // keyboard probably just became hidden
                frameLayoutParams.height = usableHeightSansKeyboard;
            }
            mChildOfContent.requestLayout();
            usableHeightPrevious = usableHeightNow;
        }
    }
    private static int computeUsableHeight() {
        Rect r = new Rect();
        mChildOfContent.getWindowVisibleDisplayFrame(r);
        return (r.bottom - r.top);
    }

    /**
     * 关闭软件盘
     */
    public static void hideKeyboard(View view, Activity activity){
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}
